#!/usr/bin/env python3
"""
Prometheus告警通知模块
支持飞书等多种通知方式
"""

import requests
import json
import logging
from datetime import datetime
from typing import Dict, Any, Optional
from config import Config

logger = logging.getLogger(__name__)

class PrometheusNotifier:
    """Prometheus告警通知器"""
    
    def __init__(self):
        self.config = Config.get_notification_config()
        self.feishu_webhook = self.config['feishu_webhook']
        self.enable_notification = self.config['enable_notification']
        self.notification_level = self.config['notification_level']
        
        logger.info(f"通知系统初始化完成，启用状态: {self.enable_notification}")
    
    def send_analysis_report(self, analysis_result: str, alert_count: int, ai_success: bool = True) -> bool:
        """发送分析报告通知"""
        if not self.enable_notification:
            logger.info("通知功能已禁用，跳过发送")
            return True
        
        try:
            # 构建通知内容
            title = f"🔔 Prometheus告警分析报告 ({alert_count}个告警)"
            
            # 选择合适的通知方式
            if self.feishu_webhook:
                return self._send_feishu_card(title, analysis_result, alert_count, ai_success)
            else:
                logger.warning("未配置任何通知方式")
                return False
                
        except Exception as e:
            logger.error(f"发送通知异常: {e}")
            return False
    
    def _send_feishu_card(self, title: str, content: str, alert_count: int, ai_success: bool) -> bool:
        """发送飞书富文本卡片通知"""
        try:
            # 确定卡片颜色
            if alert_count >= 10:
                color = "red"
            elif alert_count >= 5:
                color = "orange" 
            else:
                color = "blue"
            
            # 构建卡片消息
            card_content = {
                "msg_type": "interactive",
                "card": {
                    "config": {
                        "wide_screen_mode": True,
                        "enable_forward": True
                    },
                    "header": {
                        "template": color,
                        "title": {
                            "content": title,
                            "tag": "text"
                        }
                    },
                    "elements": [
                        {
                            "tag": "div",
                            "text": {
                                "content": self._format_content_for_feishu(content),
                                "tag": "lark_md"
                            }
                        },
                        {
                            "tag": "hr"
                        },
                        {
                            "tag": "div",
                            "fields": [
                                {
                                    "is_short": True,
                                    "text": {
                                        "content": f"**生成时间**\n{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
                                        "tag": "lark_md"
                                    }
                                },
                                {
                                    "is_short": True,
                                    "text": {
                                        "content": f"**数据源**\nPrometheus",
                                        "tag": "lark_md"
                                    }
                                }
                            ]
                        }
                    ]
                }
            }
            
            response = requests.post(
                self.feishu_webhook,
                headers={'Content-Type': 'application/json'},
                data=json.dumps(card_content),
                timeout=30
            )
            
            if response.status_code == 200:
                result = response.json()
                if result.get('StatusCode') == 0:
                    logger.info("飞书通知发送成功")
                    return True
                else:
                    logger.error(f"飞书通知发送失败: {result}")
                    return False
            else:
                logger.error(f"飞书通知请求失败: HTTP {response.status_code}")
                return False
                
        except Exception as e:
            logger.error(f"发送飞书通知异常: {e}")
            return False
    
    def send_error_notification(self, error_message: str, error_type: str = "系统错误") -> bool:
        """发送错误通知"""
        if not self.enable_notification or not self.feishu_webhook:
            return False
        
        try:
            card_content = {
                "msg_type": "interactive",
                "card": {
                    "header": {
                        "template": "red",
                        "title": {
                            "content": f"🚨 Prometheus监控系统错误",
                            "tag": "text"
                        }
                    },
                    "elements": [
                        {
                            "tag": "div",
                            "text": {
                                "content": f"**错误类型**: {error_type}\n\n**错误详情**: {error_message}\n\n**发生时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
                                "tag": "lark_md"
                            }
                        }
                    ]
                }
            }
            
            response = requests.post(
                self.feishu_webhook,
                headers={'Content-Type': 'application/json'},
                data=json.dumps(card_content),
                timeout=30
            )
            
            return response.status_code == 200
            
        except Exception as e:
            logger.error(f"发送错误通知异常: {e}")
            return False
    
    def _format_content_for_feishu(self, content: str) -> str:
        """格式化内容以适配飞书Markdown"""
        # 移除可能导致解析问题的字符
        content = content.replace('```', '')
        
        # 限制内容长度以避免消息过长
        if len(content) > 2000:
            content = content[:2000] + "\n\n...\n*内容已截断*"
        
        return content
    
    def test_notification(self) -> bool:
        """测试通知功能"""
        test_message = """**测试通知**

这是一条测试消息，用于验证Prometheus告警通知功能是否正常工作。

**测试内容**:
- ✅ 通知配置验证
- ✅ 网络连接测试
- ✅ 消息格式检查

如果您收到这条消息，说明通知功能已正常配置。"""
        
        return self.send_analysis_report(test_message, 0, True)